﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoStopData.Domains;
using AutoStopData.Model;

namespace AutoStopData.BussinessLogic
{
    public static class Users
    {
        public static void Insert(User entity)
        {
            using (var ctx = new AutoStopContext())
            {
                entity.UserId = Guid.NewGuid();
                entity.Created = DateTime.Now;
                entity.Banned = false;
                ctx.Users.AddObject(entity);
                ctx.SaveChanges();
            }
        }

        public static void Update(User entity)
        {
            using (var ctx = new AutoStopContext())
            {
                var loadedUser = ctx.Users.Where(u => u.UserId == entity.UserId).First();
                loadedUser.Banned = entity.Banned;
                loadedUser.Name = entity.Name;
                loadedUser.Contact = entity.Contact;
                ctx.SaveChanges();
            }
        }

        public static void Delete(User entity)
        {
            using (var ctx = new AutoStopContext())
            {
                var loadedUser = ctx.Users.Where(u => u.UserId == entity.UserId).First();
                loadedUser.Banned = true;
                ctx.SaveChanges();
            }
        }

        public static List<User> Select(object displayAlsoBannedUsers)
        {
            List<User> retVal;
            using (var ctx = new AutoStopContext())
            {
                var displayAlsoBannedUsersTyped = (bool)displayAlsoBannedUsers;
                var adminUserTypeCode = UserTypes.GetCode(UserTypes.Name.Administrator);
                var query = ctx.Users.Where(u => u.UserTypeCode != adminUserTypeCode);
                if (!displayAlsoBannedUsersTyped)
                {
                    query = query.Where(o => o.Banned == false);
                }
                retVal = query.OrderByDescending(u => u.Created).ToList();
            }
            return retVal;
        }

        public static User GetByMail(String mail)
        {
            User retVal;
            using (var ctx = new AutoStopContext())
            {
                var user = ctx.Users.Where(u => u.Mail.ToUpper() == mail.ToUpper()).FirstOrDefault();
                retVal = user;
            }
            return retVal;
        }

        public static void ChangePassword(Guid userId, String newPassword)
        {
            using (var ctx = new AutoStopContext())
            {
                User loadedUser = ctx.Users.Where(u => u.UserId == userId).First();
                loadedUser.Password = newPassword;
                ctx.SaveChanges();
            }
        }
    }
}
